package unq.tpi.persistencia.performanceEj.daos;

import java.util.List;

import org.hibernate.classic.Session;

import unq.tpi.persistencia.performanceEj.model.Department;
import unq.tpi.persistencia.performanceEj.model.DepartmentResume;
import unq.tpi.persistencia.performanceEj.model.EmployeeResume;
import unq.tpi.persistencia.util.SessionManager;

public class DepartmentDAO {

	public Department getByName(final String name) {
		Session session = SessionManager.getSession();
		return (Department) session
				.createQuery("from Department where name = :name")
				.setParameter("name", name).uniqueResult();
	}
	
	
	
	public DepartmentResume getDepartmentResumeByName(final String name) {
		Session session = SessionManager.getSession();
		
		String number = (String) session.createQuery("SELECT d.number FROM Department as d  where d.name = :name")
			.setParameter("name", name).uniqueResult();
		
		Integer sizeEmp = Integer.parseInt(session.createQuery("SELECT count(*) FROM Department as d inner join d.employees where d.name = :name")
				.setParameter("name", name).uniqueResult().toString()); 
				
		Integer sizeHist = Integer.parseInt(session.createQuery("SELECT count(*) FROM Department as d inner join d.historicEmployees where d.name = :name")
				.setParameter("name", name).uniqueResult().toString());
		
		
		return new DepartmentResume(number, sizeEmp, sizeHist);
	}

	public Department getByCode(String num) {
		Session session = SessionManager.getSession();
		return (Department) session.get(Department.class, num);
	}

	public List<EmployeeResume> getEmployeeResumeByCode(String num) {
		Session session = SessionManager.getSession();
		return  (List<EmployeeResume>)session
				.createQuery("select  new unq.tpi.persistencia.performanceEj.model.EmployeeResume(e.firstName , e.lastName,t,s.amount) from Department as d inner join  d.employees as e inner join e.salaries as s inner join e.titles t where d.number = :num and s.to = '9999-01-01' ")
				.setParameter("num", num).list();
	}
	@SuppressWarnings("unchecked")
	public List<Department> getAll() {
		Session session = SessionManager.getSession();
		return session.createCriteria(Department.class).list();
	}

}
